/*
 * This file is part of the MicroPython project, http://micropython.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2013, 2014, 2015 Damien P. George
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
#include <stdio.h>
#include <stdint.h>
#include <string.h>

#include "py/runtime.h"
#include "py/gc.h"
#include "py/mphal.h"
#include "extmod/virtpin.h"
#include "machine.h"

#include "wm_hal.h"


// is_name=True, 查找Pin对应的name, 否者查找GPIO的配置k(GPIO_MODE_INPUT, GPIO_MODE_OUTPUT)对应的显示信息("input", "output")
const char* gpio_search(uint8_t pin, bool is_name, int k)
{
    STATIC const char* _pina_nm[16] = {
        "PA0",  "PA1",  "PA2",  "PA3", 
        "PA4",  "PA5",  "PA6",  "PA7", 
        "PA8",  "PA9",  "PA10", "PA11", 
        "PA12", "PA13", "PA14", "PA15", 
    };
    STATIC const char* _pinb_nm[32] = {
        "PB0",  "PB1",  "PB2",  "PB3", 
        "PB4",  "PB5",  "PB6",  "PB7", 
        "PB8",  "PB9",  "PB10", "PB11", 
        "PB12", "PB13", "PB14", "PB15", 
        "PB16", "PB17", "PB18", "PB19", 
        "PB20", "PB21", "PB22", "PB23", 
        "PB24", "PB25", "PB26", "PB27", 
        "PB28", "PB29", "PB30", "PB31",
    };
    STATIC const struct{
        uint8_t key;
        const char* val;
    }_info_map[] = {
        {.key=GPIO_MODE_INPUT, .val="input"},
        {.key=GPIO_MODE_OUTPUT, .val="output"},
        {.key=GPIO_MODE_IT_RISING, .val="trig_rising"},
        {.key=GPIO_MODE_IT_FALLING, .val="trig_falling"},
        //{.key=GPIO_MODE_IT_RISING_FALLING, .val="trig_both_edge"},
        //{.key=GPIO_MODE_IT_HIGH_LEVEL, .val="trig_high"},
        //{.key=GPIO_MODE_IT_LOW_LEVEL, .val="trig_low"},
        {.key=GPIO_NOPULL, .val="no"},
        {.key=GPIO_PULLUP, .val="up"},
        {.key=GPIO_PULLDOWN, .val="dwn"},
    };
    
    if(is_name){
        return  (MICROPY_HW_PORT_IDX(pin) == 1) ? (_pinb_nm[MICROPY_HW_PIN_IDX(pin)]) : (_pina_nm[MICROPY_HW_PIN_IDX(pin)]);
    }else{
        for(int i = 0; i < ARR_LEN(_info_map); i++){
            if(_info_map[i].key == k){
                return _info_map[i].val;
            }
        }
    }
    return "";
}

STATIC void machine_pin_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
    machine_pin_obj_t *self = self_in;
    mp_printf(print, "Pin(nm=%s, mode=%s, pull=%s, hardirq)", gpio_search(self->pin, true, 0), gpio_search(self->pin, false, self->mode), gpio_search(self->pin, false, self->pull));
}

// pin.init(mode, pull=None, *, value, callback)
STATIC mp_obj_t machine_pin_obj_init_helper(machine_pin_obj_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
    enum { ARG_mode, ARG_pull, ARG_value, ARG_callback };
    static const mp_arg_t allowed_args[] = {
        { MP_QSTR_mode, MP_ARG_REQUIRED | MP_ARG_INT },
        { MP_QSTR_pull, MP_ARG_OBJ, {.u_obj = mp_const_none}},
        { MP_QSTR_value, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}},
        { MP_QSTR_callback, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}},
    };
    
    GPIO_InitTypeDef init;
    __HAL_RCC_GPIO_CLK_ENABLE();

    // parse args
    mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
    mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);

    // close af func
    GPIO_AF_DISABLE(self->pin);

    // get io mode
    self->mode = args[ARG_mode].u_int;
    // get pull mode
    self->pull = (args[ARG_pull].u_obj != mp_const_none) ? (mp_obj_get_int(args[ARG_pull].u_obj)) : (GPIO_NOPULL);
    // get initial value
    int value = (args[ARG_value].u_obj != MP_OBJ_NULL) ? (mp_obj_is_true(args[ARG_value].u_obj)) : (-1);
    // exti callback
    self->callback = (args[ARG_callback].u_obj == MP_OBJ_NULL) ? (mp_const_none) : (args[ARG_callback].u_obj);
    // init gpio
    init.Pin = MICROPY_HW_PIN(self->pin);
    init.Mode = self->mode;
    init.Pull = self->pull;
    SET_BIT(MICROPY_HW_PORT(self->pin)->IC, init.Pin);   // clear exti interrupt flag
    HAL_GPIO_Init(MICROPY_HW_PORT(self->pin), &init);    // init gpio

    // set value if output mode
    if(self->mode == GPIO_MODE_OUTPUT){
        HAL_GPIO_WritePin(MICROPY_HW_PORT(self->pin), MICROPY_HW_PIN(self->pin), (GPIO_PinState)value);
    }
    return mp_const_none;
}

// constructor(id, [mode, pull ,value, callback])
mp_obj_t mp_pin_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
    mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);

    // get the wanted pin object
    machine_pin_obj_t *pin = NULL;
    int pin_nr = mp_obj_get_int(args[0]);
    int offs = (MICROPY_HW_PORT_IDX(pin_nr) ? (16) : (0)) + MICROPY_HW_PIN_IDX(pin_nr);
    
    if(offs < 0 || offs > ARR_LEN(MP_STATE_PORT(pin_obj_all))){
        mp_raise_ValueError(MP_ERROR_TEXT("invalid pin"));
    }
    if(pin == NULL){
        pin = m_new0(machine_pin_obj_t, 1);
        MP_STATE_PORT(pin_obj_all)[offs] = pin;
        pin->base.type = &machine_pin_type;
        pin->pin = pin_nr;
    }else{
        pin = MP_STATE_PORT(pin_obj_all)[offs];
    }
    
    if (n_args > 1 || n_kw > 0) {
        // pin mode given, so configure this GPIO
        mp_map_t kw_args;
        mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
        machine_pin_obj_init_helper(pin, n_args - 1, args + 1, &kw_args);
    }
    if(MICROPY_HW_PORT_IDX(pin_nr)){
        HAL_NVIC_SetPriority(GPIOB_IRQn, MICROPY_HW_GPIOB_PRI);
	    HAL_NVIC_EnableIRQ(GPIOB_IRQn);
    }else{
        HAL_NVIC_SetPriority(GPIOA_IRQn, MICROPY_HW_GPIOA_PRI);
	    HAL_NVIC_EnableIRQ(GPIOA_IRQn);
    }
    return MP_OBJ_FROM_PTR(pin);
}

// pin.init(mode, pull [,value, callback])
STATIC mp_obj_t machine_pin_obj_init(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
    return machine_pin_obj_init_helper(args[0], n_args - 1, args + 1, kw_args);
}
MP_DEFINE_CONST_FUN_OBJ_KW(machine_pin_init_obj, 1, machine_pin_obj_init);

// pin.deinit()
STATIC mp_obj_t machine_pin_deinit(mp_obj_t self_in) {
    machine_pin_obj_t *self = self_in;
    HAL_GPIO_DeInit(MICROPY_HW_PORT(self->pin), MICROPY_HW_PIN(self->pin));
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_pin_deinit_obj, machine_pin_deinit);


// fast method for getting/setting pin value
STATIC mp_obj_t machine_pin_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
    mp_arg_check_num(n_args, n_kw, 0, 1, false);
    machine_pin_obj_t *self = self_in;
    if (n_args == 0) {
        // get pin
        return MP_OBJ_NEW_SMALL_INT(HAL_GPIO_ReadPin(MICROPY_HW_PORT(self->pin), MICROPY_HW_PIN(self->pin)));
    } else {
        // set pin
        HAL_GPIO_WritePin(MICROPY_HW_PORT(self->pin), MICROPY_HW_PIN(self->pin), (GPIO_PinState)mp_obj_is_true(args[0]));
        return mp_const_none;
    }
}

// pin.value([value])
STATIC mp_obj_t machine_pin_value(size_t n_args, const mp_obj_t *args) {
    return machine_pin_call(args[0], n_args - 1, 0, args + 1);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_pin_value_obj, 1, 2, machine_pin_value);

STATIC mp_obj_t machine_pin_off(mp_obj_t self_in) {
    machine_pin_obj_t *self = self_in;
    HAL_GPIO_WritePin(MICROPY_HW_PORT(self->pin), MICROPY_HW_PIN(self->pin), GPIO_PIN_RESET);
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_pin_off_obj, machine_pin_off);

STATIC mp_obj_t machine_pin_on(mp_obj_t self_in) {
    machine_pin_obj_t *self = self_in;
    HAL_GPIO_WritePin(MICROPY_HW_PORT(self->pin), MICROPY_HW_PIN(self->pin), GPIO_PIN_SET);
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_pin_on_obj, machine_pin_on);

STATIC mp_obj_t machine_pin_toggle(mp_obj_t self_in) {
    machine_pin_obj_t *self = self_in;
    HAL_GPIO_TogglePin(MICROPY_HW_PORT(self->pin), MICROPY_HW_PIN(self->pin));
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_pin_toggle_obj, machine_pin_toggle);

STATIC mp_uint_t pin_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) {
    (void)errcode;
    machine_pin_obj_t *self = self_in;

    switch (request) {
        case MP_PIN_READ: {
            return HAL_GPIO_ReadPin(MICROPY_HW_PORT(self->pin), MICROPY_HW_PIN(self->pin)); 
        }
        case MP_PIN_WRITE: {
            HAL_GPIO_WritePin(MICROPY_HW_PORT(self->pin), MICROPY_HW_PIN(self->pin), (GPIO_PinState)arg);
            return 0;
        }
    }
    return -1;
}

STATIC const mp_rom_map_elem_t machine_pin_locals_dict_table[] = {
    // GPIOA 
    { MP_ROM_QSTR(MP_QSTR_PA0),    MP_OBJ_NEW_SMALL_INT(PA0) },
    { MP_ROM_QSTR(MP_QSTR_PA1),    MP_OBJ_NEW_SMALL_INT(PA1) },
    { MP_ROM_QSTR(MP_QSTR_PA2),    MP_OBJ_NEW_SMALL_INT(PA2) },
    { MP_ROM_QSTR(MP_QSTR_PA3),    MP_OBJ_NEW_SMALL_INT(PA3) },
    { MP_ROM_QSTR(MP_QSTR_PA4),    MP_OBJ_NEW_SMALL_INT(PA4) },
    { MP_ROM_QSTR(MP_QSTR_PA5),    MP_OBJ_NEW_SMALL_INT(PA5) },
    { MP_ROM_QSTR(MP_QSTR_PA6),    MP_OBJ_NEW_SMALL_INT(PA6) },
    { MP_ROM_QSTR(MP_QSTR_PA7),    MP_OBJ_NEW_SMALL_INT(PA7) },
    { MP_ROM_QSTR(MP_QSTR_PA8),    MP_OBJ_NEW_SMALL_INT(PA8) },
    { MP_ROM_QSTR(MP_QSTR_PA9),    MP_OBJ_NEW_SMALL_INT(PA9) },
    { MP_ROM_QSTR(MP_QSTR_PA10),    MP_OBJ_NEW_SMALL_INT(PA10) },
    { MP_ROM_QSTR(MP_QSTR_PA11),    MP_OBJ_NEW_SMALL_INT(PA11) },
    { MP_ROM_QSTR(MP_QSTR_PA12),    MP_OBJ_NEW_SMALL_INT(PA12) },
    { MP_ROM_QSTR(MP_QSTR_PA13),    MP_OBJ_NEW_SMALL_INT(PA13) },
    { MP_ROM_QSTR(MP_QSTR_PA14),    MP_OBJ_NEW_SMALL_INT(PA14) },
    { MP_ROM_QSTR(MP_QSTR_PA15),    MP_OBJ_NEW_SMALL_INT(PA15) },
    // GPIOB
    { MP_ROM_QSTR(MP_QSTR_PB0),    MP_OBJ_NEW_SMALL_INT(PB0) },
    { MP_ROM_QSTR(MP_QSTR_PB1),    MP_OBJ_NEW_SMALL_INT(PB1) },
    { MP_ROM_QSTR(MP_QSTR_PB2),    MP_OBJ_NEW_SMALL_INT(PB2) },
    { MP_ROM_QSTR(MP_QSTR_PB3),    MP_OBJ_NEW_SMALL_INT(PB3) },
    { MP_ROM_QSTR(MP_QSTR_PB4),    MP_OBJ_NEW_SMALL_INT(PB4) },
    { MP_ROM_QSTR(MP_QSTR_PB5),    MP_OBJ_NEW_SMALL_INT(PB5) },
    { MP_ROM_QSTR(MP_QSTR_PB6),    MP_OBJ_NEW_SMALL_INT(PB6) },
    { MP_ROM_QSTR(MP_QSTR_PB7),    MP_OBJ_NEW_SMALL_INT(PB7) },
    { MP_ROM_QSTR(MP_QSTR_PB8),    MP_OBJ_NEW_SMALL_INT(PB8) },    
    { MP_ROM_QSTR(MP_QSTR_PB9),    MP_OBJ_NEW_SMALL_INT(PB9) },
    { MP_ROM_QSTR(MP_QSTR_PB10),    MP_OBJ_NEW_SMALL_INT(PB10) },
    { MP_ROM_QSTR(MP_QSTR_PB11),    MP_OBJ_NEW_SMALL_INT(PB11) },
    { MP_ROM_QSTR(MP_QSTR_PB12),    MP_OBJ_NEW_SMALL_INT(PB12) },
    { MP_ROM_QSTR(MP_QSTR_PB13),    MP_OBJ_NEW_SMALL_INT(PB13) },
    { MP_ROM_QSTR(MP_QSTR_PB14),    MP_OBJ_NEW_SMALL_INT(PB14) },
    { MP_ROM_QSTR(MP_QSTR_PB15),    MP_OBJ_NEW_SMALL_INT(PB15) },
    { MP_ROM_QSTR(MP_QSTR_PB16),    MP_OBJ_NEW_SMALL_INT(PB16) },
    { MP_ROM_QSTR(MP_QSTR_PB17),    MP_OBJ_NEW_SMALL_INT(PB17) },    
    { MP_ROM_QSTR(MP_QSTR_PB18),    MP_OBJ_NEW_SMALL_INT(PB18) },
    { MP_ROM_QSTR(MP_QSTR_PB19),    MP_OBJ_NEW_SMALL_INT(PB19) },
    { MP_ROM_QSTR(MP_QSTR_PB20),    MP_OBJ_NEW_SMALL_INT(PB20) },
    
    { MP_ROM_QSTR(MP_QSTR_PB21),    MP_OBJ_NEW_SMALL_INT(PB21) },
    { MP_ROM_QSTR(MP_QSTR_PB22),    MP_OBJ_NEW_SMALL_INT(PB22) },
    { MP_ROM_QSTR(MP_QSTR_PB24),    MP_OBJ_NEW_SMALL_INT(PB24) },
    { MP_ROM_QSTR(MP_QSTR_PB25),    MP_OBJ_NEW_SMALL_INT(PB25) },
    { MP_ROM_QSTR(MP_QSTR_PB26),    MP_OBJ_NEW_SMALL_INT(PB26) },
    { MP_ROM_QSTR(MP_QSTR_PB27),    MP_OBJ_NEW_SMALL_INT(PB27) },    

    // instance methods
    { MP_ROM_QSTR(MP_QSTR_init),    MP_ROM_PTR(&machine_pin_init_obj) },
    { MP_ROM_QSTR(MP_QSTR_deinit),  MP_ROM_PTR(&machine_pin_deinit_obj) },
    { MP_ROM_QSTR(MP_QSTR_value),   MP_ROM_PTR(&machine_pin_value_obj) },
    { MP_ROM_QSTR(MP_QSTR_off),     MP_ROM_PTR(&machine_pin_off_obj) },
    { MP_ROM_QSTR(MP_QSTR_on),      MP_ROM_PTR(&machine_pin_on_obj) },
    {MP_ROM_QSTR(MP_QSTR_toggle), MP_ROM_PTR(&machine_pin_toggle_obj) },

    // class constants
    { MP_ROM_QSTR(MP_QSTR_MODE_IN),  MP_ROM_INT(GPIO_MODE_INPUT) },
    { MP_ROM_QSTR(MP_QSTR_MODE_OUT), MP_ROM_INT(GPIO_MODE_OUTPUT) },
    // mode for interrupt(exti)
    { MP_ROM_QSTR(MP_QSTR_MODE_IT_RISING),  MP_ROM_INT(GPIO_MODE_IT_RISING) },
    { MP_ROM_QSTR(MP_QSTR_MODE_IT_FALLING), MP_ROM_INT(GPIO_MODE_IT_FALLING) },
    // pull select
    { MP_ROM_QSTR(MP_QSTR_PULL_UP),   MP_ROM_INT(GPIO_PULLUP) },
    { MP_ROM_QSTR(MP_QSTR_PULL_DOWN), MP_ROM_INT(GPIO_PULLDOWN) },
    { MP_ROM_QSTR(MP_QSTR_PULL_NONE), MP_ROM_INT(GPIO_NOPULL) },
};

STATIC MP_DEFINE_CONST_DICT(machine_pin_locals_dict, machine_pin_locals_dict_table);

STATIC const mp_pin_p_t pin_pin_p = {
    .ioctl = pin_ioctl,
};

const mp_obj_type_t machine_pin_type = {
    { &mp_type_type },
    .name = MP_QSTR_Pin,
    .print = machine_pin_print,
    .make_new = mp_pin_make_new,
    .call = machine_pin_call,
    .protocol = &pin_pin_p,
    .locals_dict = (mp_obj_dict_t *)&machine_pin_locals_dict,
};



